<?php
/*
* 龙啸轩WEB开发框架PHP版 BY Cdeng in Lhasa “不会画画的编程爱好者不是一个好木匠”
*/
const CXUU_V = "CxuuWeb.PHP V3.7.3";

/**
 * 输出json格式数据 供LAYUI数据表格使用
 * @param  [type] $data [description]
 * @return [type]       [description]
 */
function jsonList($data)
{
	$js = [
		'code' => 0,
		'msg' => 'ok',
		'count' => $data['page']['rows'],
		'data' => $data['data']
	];
	exit(json_encode($js));
}

/* 
 *  获取系统配置信息方法
 *  使用方法：在模板<?php echo siteInfo('copyright');?> 
 */
function siteInfo($key)
{
	$v = new \model\siteconfig;
	return $v->getSiteInfo($key);
}

/**
 * 写入数据库操作日志
 * SqlLog($info);
 * **/
function SqlLog(string $info, int $userid = null)
{
	$log_sql = new \model\log_sql();
	$log_sql->insertData($info, $userid);
}

/**
 * 清除数据库缓存
 * CleanDbCache($table);
 * **/
function CleanDbCache(string $table)
{
	$pdo = \libs\pdo::Init();
	$prefix = $pdo->GetConfig();
	$pdo->CleanCache($GLOBALS['ZPHP_CONFIG']['DB']['db'], $prefix['prefix'] . $table);
}
/* 
 *  加载后台语言包
 *  使用方法：在模板<?php echo lang('home');?>   输出：后台首页
 */
function lang($val, $l = 'zh-cn')
{
	$lang = GetCxuuCache('langCache');
	if (empty($lang)) {
		$lang = include_once(P_APP . "/base/lang/" . $l . ".php");
		SetCxuuCache('langCache', $lang);
	}
	return $lang[$val];
}
/* 
 *  生成后台常用路径 生成 admin.php?c=member&a=del  后台部分未使用路由模式，使用这种方式较好
 *  使用方法：在模板<?php echo CAUrl('member','del');?> 
 */
function CAUrl($c, $a)
{
	return PHP_FILE . '?c=' . $c . '&a=' . $a;
}


/* 
 *  获取 当前登录用户信息
 *  使用方法：在模板<?php echo LoginUserInfo("nickname");?> 
 */
function LoginUserInfo($val)
{
	//$userid = $_SESSION['cxuu_admin']["userid"];
	$cookie = unserialize(Decrypt($_COOKIE['cxuuweb_php_login'], $GLOBALS['ZPHP_CONFIG']['SYSTEMNAME']));
	$userid = $cookie["userid"];
	if (empty($userid)) return; //判断用户是否登录，没有登录返回
	$u = new model\admin_user;
	$adminUserInfo = $u->findData($userid);
	$g = new model\admin_group;
	$adminGroupInfo = $g->findData($adminUserInfo['gid']);
	$info = [
		'userstatus' => $adminUserInfo['status'],
		'userid' => $adminUserInfo['id'],
		'username' => $adminUserInfo['username'],
		'gid' => $adminUserInfo['gid'],
		'nickname' => $adminUserInfo['nickname'],
		'photo' => $adminUserInfo['photo'],
		'phone' => $adminUserInfo['phone'],
		"groupname" => $adminGroupInfo['groupname'],
		"channlrole" => $adminGroupInfo['channlrole'],
		"systemrole" => $adminGroupInfo['systemrole'],
	];
	return $info[$val];
}

/* 
 *  对比数组是否有指定值  3.7.3 已弃用
 *  返回 checkbox 选定状态
 *  使用方法：用于系统权限设置页<?php echo SysRoC("siteconfig_index",$systemrole);?>
 */
function SysRoC($val, $arr)
{
	return is_array($arr) && in_array($val, $arr) ? 'checked' : '';
}

/* 
 *  判断是否拥有的系统功能权限
 $val 为权限值，如： articlecontent_addview
 */
function SysRolCk($val)
{
	//return LoginUserInfo("gid") == 1 || in_array(strtolower($val), array_map('strtolower', JsonDecode(LoginUserInfo("systemrole"))));
	return LoginUserInfo("gid") == 1 || in_array(strtolower($val), JsonDecode(LoginUserInfo("systemrole")));
}


/* 
 *  拓展Redis 获取全部key 计算有多少条 缓存数据
 *  =================================
 *	$c->keys('*') 全部KEY
 *  
 */
function RCA()
{
	if ($GLOBALS['ZPHP_CONFIG']['DB']['cache_mod'] == 1) {
		$c = libs\cache::Redis();
		return count($c->keys('z-php-lock'));
	} else {
		return 0;
	}
}

/* 
 *  后台栏目列表
 *  =================================
 *	引用方式实现无限极分类
 *  使用方法：generateTree($data)
 */
function GenerateTree($data)
{
	$items = array();
	foreach ($data as $v) {
		$items[$v['id']] = $v;
	}
	$tree = array();
	foreach ($items as $k => $item) {
		if (isset($items[$item['pid']])) {
			$items[$item['pid']]['haveChild'] = true;
			$items[$item['pid']]['href'] = true;
			$items[$item['pid']]['open'] = true;
			$items[$item['pid']]['spread'] = "true";
			$items[$item['pid']]['children'][] = &$items[$k];
		} else {
			$tree[] = &$items[$k];
		}
	}
	return $tree;
}


/* 
 *  后台 内容管理 栏目分类菜单
 *  =================================
 *	引用方式实现无限极分类
 *  使用方法：ContentCateTree($data)
 */
function ContentCateTree($data)
{
	$dataRename = array();
	foreach ($data as $key => $newdata) {
		$dataRename[$key]['id'] = $data[$key]['id'];
		$dataRename[$key]['parentId'] = $data[$key]['pid'];
		$dataRename[$key]['title'] = $data[$key]['name'];
		$dataRename[$key]['type'] = $data[$key]['type'];

		if ($dataRename[$key]['type'] == 0) {
			$dataRename[$key]['disabled'] = "true";
			$dataRename[$key]['spread'] = "true";
		}
	}

	$items = array();
	foreach ($dataRename as $v) {
		$items[$v['id']] = $v;
	}
	$tree = array();
	foreach ($items as $k => $item) {
		if (isset($items[$item['parentId']]))
			$items[$item['parentId']]['children'][] = &$items[$k];
		else
			$tree[] = &$items[$k];
	}
	return $tree;
}

/* 
 *  递归方式实现无限极分类
 *  使用方法：GetTree($data)
 */
function GetTree($arr, $pid = 0, $level = 0)
{
	static $list = [];
	foreach ($arr as $key => $value) {
		if ($value["pid"] == $pid) {
			$value["level"] = $level;
			$value["open"] = true;
			$list[] = $value;
			unset($arr[$key]); //删除已经排好的数据为了减少遍历的次数
			GetTree($arr, $value["id"], $level + 1);
		}
	}
	return $list;
}

/** 
 * 统计目录文件大小
 */
function DirSize($file)
{
	$size = 0;
	if (is_dir($file)) {
		$dir = opendir($file);
		while (false !== ($filename = readdir($dir))) {
			if ($filename != "." && $filename != "..") {
				$filename = $file . "/" . $filename;
				if (is_dir($filename))
					$size += DirSize($filename);
				else
					$size += filesize($filename);
			}
		}
		closedir($dir);
		return $size;
	} else {
		return 0;
	}
}

/** 
 * 统计目录文件大小
 */
$fileNum = 0;
$dirNum = 0;
function DirFileSize($file)
{
	global $fileNum;
	global $dirNum;
	//count(glob($file."*"));
	if (is_dir($file)) {
		$dir = opendir($file);
		while (false !== ($filename = readdir($dir))) {
			if ($filename != "." && $filename != "..") {
				$filename = $file . "/" . $filename;
				if (is_dir($filename)) {
					$dirNum += 1;
					DirFileSize($filename);
				} else {
					$fileNum += 1;
				}
			}
		}
		closedir($dir);
		return ['fileNum' => $fileNum, 'dirNum' => $dirNum];
	} else {
		return 0;
	}
}


/**
 * 删除P_PUBLIC文件
 * @param  [type]url string  $path 主要为附件地址 如：/uploads/attment/202005/10/5eb79b20964504346290.txt
 * DelFile('/uploads/attment/202005/10/5eb7830069d7e2556290.txt');
 */

function DelFile(string $path)
{
	$path = P_PUBLIC . $path;
	$url = iconv('utf-8', 'gbk', $path);
	if (PATH_SEPARATOR == ':')  //linux
		unlink($path);
	else
		unlink($url);
}


/**
 * 获取文件目录列表
 * @param string $pathname 路径
 * @param integer $fileFlag 文件列表 0所有文件列表,1只读文件夹,2是只读文件(不包含文件夹)
 * @param string $pattern  文件类型 * 所有文件  *.html  为所有html文件
 * @return array
 */
function GetFileFolderList($pathname, $fileFlag = 0, $pattern = '*')
{
	$fileArray = array();
	$pathname = rtrim($pathname, '/') . '/';
	$list   =   glob($pathname . $pattern);
	foreach ($list  as $i => $file) {
		switch ($fileFlag) {
			case 0:
				$fileArray[] = basename($file);
				break;
			case 1:
				if (is_dir($file))
					$fileArray[] = basename($file);
				break;
			case 2:
				if (is_file($file))
					$fileArray[] = basename($file);
				break;
			default:
				break;
		}
	}
	if (empty($fileArray)) $fileArray = NULL;
	return $fileArray;
}
